package org.example;

public class Solution22 {

    public static class ListNode {

        int val;

        ListNode next;

        ListNode(int x) {
            val = x;
            next = null;
        }
    }

    public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
        // 判断链表是否为空
        if (headA == null || headB == null) {
            return null;
        }

        // 初始化两个指针，分别指向两个链表的头节点
        ListNode pointerA = headA;
        ListNode pointerB = headB;

        // 遍历链表
        // 当 pointerA 或 pointerB 到达链表末尾时，将其重定位到另一个链表的头节点。这样可以确保两个指针在第二次遍历时能够同步到达相交节点或 null
        while (pointerA != pointerB) {
            pointerA = (pointerA == null) ? headB : pointerA.next;
            pointerB = (pointerB == null) ? headA : pointerB.next;
        }

        return pointerA;
    }

}
